package de.jmda.gen.java.impl;

import static de.jmda.util.StringUtil.sb;
import de.jmda.gen.GeneratorException;
import de.jmda.gen.impl.DefaultGenerator;
import de.jmda.gen.java.AnnotationStatementGenerator;
import de.jmda.util.StringUtil;

public class DefaultAnnotationStatementGenerator
		extends DefaultGenerator
		implements AnnotationStatementGenerator
{
	public DefaultAnnotationStatementGenerator(String annotationStatement)
  {
	  super(annotationStatement);
  }

	public DefaultAnnotationStatementGenerator(Class<?> annotation)
  {
		this(annotation, null);
  }

	public DefaultAnnotationStatementGenerator(
			Class<?> annotation, StringBuffer parameters)
  {
		super();

		if (annotation == null)
		{
			throw new IllegalArgumentException("'annotation' must not be null");
		}

		StringBuffer annotationStatement =
				sb("@" + annotation.getName().replaceAll("\\$", "."));
		
		if (StringUtil.isEmpty(parameters))
		{
			setOutput(annotationStatement);
		}
		else
		{
			setOutput(
					annotationStatement.append("(").append(parameters).append(")"));
		}
  }

	@Override
	public StringBuffer generate() throws GeneratorException
	{
		return validate(super.generate());
	}

	/**
	 * @param stringBuffer
	 * @return <code>stringBuffer</code>
	 * @throws GeneratorException if <code>stringBuffer</code> does not start with
	 *                            <code>@</code>
	 */
	protected StringBuffer validate(StringBuffer annotationStatement)
			throws GeneratorException
	{
		if (annotationStatement.indexOf("@") != 0)
		{
			throw new GeneratorException(
					"annotation statement [" + annotationStatement +
					"] has to start with '@'");
		}

		return annotationStatement;
	}
}